package com.starblink.android.guang.activeconfig.ui

import android.content.Intent
import android.os.Bundle
import com.starblink.android.basic.appupdate.AppUpdateManager
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.config.ColdLaunchConfig
import com.starblink.android.basic.data.GaidReportManager
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.imgpreload.PreloadResImgUtils
import com.starblink.android.basic.network.base.BaseSiteSwitch
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.guang.MainActivity
import com.starblink.android.guang.databinding.ActivityActiveConfigBinding
import com.starblink.basic.ext.load
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.storage.SkStorage
import com.starblink.preferenceconfig.bean.PreferenceBrand
import com.starblink.preferenceconfig.brandchoice.ui.BrandChoiceActivity
import com.starblink.rocketreserver.fragment.SiteVOF

/**
 *
 * 开机屏广告页
 */
//@Route(path = RoutePage.ImageSearch.PAGE_CAMERA)
class ActiveConfigActivity : BaseTVMActivity<ActivityActiveConfigBinding, ActiveConfigVM>() {

    var shutdownNum = 4

    override fun initViewBinding(): ActivityActiveConfigBinding =
        ActivityActiveConfigBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 切换站点优先级最高
        handleSwitchSite()
    }

    private fun secondAction() {
        // 检查更新前置
        AppUpdateManager.checkUpdate()
        GaidReportManager.reportDeviceId(this)

        viewModel.goToMainPageLD.observe(this) {
            goToMainPage(it)
        }
        viewModel.goToBrandPreferencePageLD.observe(this) {
            goToBrandPreferencePage(it)
        }

        // 如果用户未设置过品牌偏好，先去设置
        // 否则，如果存在预加载广告图片，显示广告图片，4S后自动关闭，跳转首页
        // 否则，直接跳转首页
        if (!SkStorage.getBoolean(ColdLaunchConfig.PREFERENCE_CONFIG_CHOOSE_OR_NOT, false)) {
            SKLogger.e("dss2", "未选择偏好品牌，加载偏好品牌列表")
            viewModel.loadPreferenceBrands()
        } else {
            val resF = PreloadResImgUtils.popOneResourceF(PreloadResImgUtils.LAUNCH_PAGE)
            if (resF?.mainPic != null) {
                SKLogger.e("dss2", "有广告，显示广告")
                pageExposure(pageElementValue = SpmPageDef.PageActiveOpen)
                viewBinding.adImg.load(resF.mainPic, errorCall = {
                    viewModel.gotoMainPage()
                })

                val downTimer = FlowCountDownTimer(time = 3)

                viewBinding.shutdownLay.visible()
                viewBinding.shutdownLay.trackData(
                    page = SpmPageDef.PageActiveOpen,
                    element = SpmElementDef.PreferenceSkipButton,
                    onlyHit = true
                )
                viewBinding.shutdownLay.click {
                    downTimer.cancel()
                    viewModel.gotoMainPage()
                }
                viewBinding.adImg.trackData(
                    page = SpmPageDef.PageActiveOpen,
                    element = SpmElementDef.FolloeingRouteClick,
                    onlyHit = true
                )
                viewBinding.adImg.click {
                    resF.jumpUrl?.let {
                        downTimer.cancel()
                        viewModel.gotoMainPage(it)
                    }
                }
                viewBinding.shutdownTxt.text = "skip 0${shutdownNum}"
                downTimer.start(callBack = {
                    shutdownNum -= 1
                    if (shutdownNum != 0) {
                        viewBinding.shutdownTxt.text = "skip 0${shutdownNum}"
                    }
                }, onFinish = {
                    viewModel.gotoMainPage()
                })
            } else {
                SKLogger.e("dss2", "没有广告，直接跳转首页")
                viewModel.gotoMainPage()
            }
        }
    }

    /**
     * 处理切换站点
     */
    private fun handleSwitchSite() {
        //测试人员手动切环境
        if (BaseSiteSwitch.isQaUse()) {
            secondAction()
        } else if (BaseSiteSwitch.isCI()) {
            BaseSiteSwitch.startUpPageSwitchSite(SiteVOF(code = "", type = 1, countryCode = "GB"))
            secondAction()
        } else {
            if (!SkStorage.getBoolean(BaseSiteSwitch.START_UP_SITE_FIRST, false)) {
                viewModel.getSite { site ->
                    if (site?.code != null && site.type != null && site.countryCode != null) {
                        //读取成功,以当前ip为准
                        //失败，默认为美国IP，因为当前版本主推美国
                        BaseSiteSwitch.startUpPageSwitchSite(site)
                        secondAction()
                        SkStorage.put(BaseSiteSwitch.START_UP_SITE_FIRST, true)
                    } else {
                        secondAction()
                    }
                }
            } else {
                secondAction()
            }
        }
    }

    private fun goToMainPage(url: String? = null) {
        SKLogger.e("dss2", "goToMainPage")
        var intent = Intent(applicationContext, MainActivity::class.java)
        // 当APP处于后台 或者 APP未启动时，APP收到FCM消息，系统会弹出消息通知，用户点击通知，会启动APP主Activity
        // 通知携带的数据载荷，在主Activity的Intent.extras中查看
        getIntent().extras?.let {
            intent.putExtras(it)
        }
        url?.let {
            //handleActivePageJumpUrl MainActivity的方法对应这里
            intent.putExtra("jumpUrl", url)
        }
        startActivity(intent)
        finish()
    }

    private fun goToBrandPreferencePage(preferenceBrands: List<PreferenceBrand>) {
        SKLogger.e("dss2", "goToBrandPreferencePage")
        var intent = Intent(applicationContext, BrandChoiceActivity::class.java)
        // 当APP处于后台 或者 APP未启动时，APP收到FCM消息，系统会弹出消息通知，用户点击通知，会启动APP主Activity
        // 通知携带的数据载荷，在主Activity的Intent.extras中查看
        getIntent().extras?.let {
            intent.putExtras(it)
        }
        intent.putExtra(
            RoutePage.PreferenceConfig.ARGS_PFEFERENCE_BRANDS,
            preferenceBrands.toJson()
        )
        startActivity(intent)
        finish()
    }
}